import os
from flask import Flask, redirect, render_template, request, send_file, session, url_for
from voi_2_text import *
from translate_ch5en import *
from my_util import Logger

loger = Logger()

app = Flask(__name__)
app.secret_key = 'RyVzs9ObLV5wsTDHN0h6X1VP1jmi6UgYNGWZXPgNwKI='

UPLOAD_FOLDER = os.path.join(os.path.join(os.getcwd(), 'src', 'upload-audio'))
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

init_voice_recognize_models()  # 初始化中英语音识别模型
init_text_translate_models()  # 初始化中英文翻译模型

@app.route('/src/<path:path>')#网页的所有文件都是来自服务器
def send_image(path):
    return send_file(path, mimetype='image/jpeg')

@app.route('/')
def hello_world():  # put application's code here
    session.clear()
    loger.debug('Hello World!')
    return redirect('/home')


@app.route('/home', methods=['GET', 'POST'])
def home():
    if request.method == 'POST':
        session.clear()
        if request.form.get('choice') == 'ch2en':
            loger.info('choice is chinese translate to english')
            return redirect('/ch2en')
        elif request.form.get('choice') == 'en2ch':
            loger.info('choice is english translate to chinese')
            return redirect('/en2ch')
        else:
            loger.info('unsupported choice')
            return redirect('/home')
    return render_template('home.html')

@app.route('/upload-url', methods=['POST'])  # 访问的路径
def upload_url(): # put application's code here# '
    if request.method == "POST":
        if request.files.get("audioFile"): # !!!!!!!!!!!注意保存的录音文件还不是wav格式的，应该是哪里出错了20240526-2221
            audio_file = request.files["audioFile"]
            if audio_file is not None:
                loger.info(f"get voice ok, file length {audio_file.content_length}")
                loger.info(f"get file name {audio_file.filename}")
                # 设置保存文件的路径
                file_path = os.path.join(app.config['UPLOAD_FOLDER'], audio_file.filename)
                # 保存文件
                audio_file.save(file_path)
                loger.info(f"save file path {file_path}")
                loger.info(f"save file {audio_file.filename} length: {os.path.getsize(file_path)} bytes")
                if session.get('previous_route', 'unknown') == "ch2en":
                    result = convert_ch_voi2text(file_path)
                    loger.info(f"recognized [ch2en] result: {result[0]}")
                    session['input'] = result[0]
                elif session.get('previous_route', 'unknown') == "en2ch":
                    result = convert_en_voi2text(file_path)
                    loger.info(f"recognized [en2ch] result: {result[0]}")
                    session['input'] = result[0]
                else:
                    loger.warning(f"unsupported previous route: {session.get('previous_route', 'unknown')}")
            else:
                loger.error("empty")
    loger.debug(f"previous route is {session.get('previous_route', 'unknown')}")
    return redirect(url_for(session.get('previous_route', 'unknown')))

@app.route('/ch2en', methods=['GET', 'POST'])
def ch2en():
    loger.info(f'now in chinese translate to english')
    data = {'input': session.get('input', '你好'), 'output': 'hello'}
    if request.method == 'POST':
        session.clear()
        question = request.form.get("inputTxt")
        loger.info(f"get input text {question}")
        translate = translate_ch2en(question)
        data = {'input': question, 'output': translate}
    session['previous_route'] = 'ch2en'
    return render_template('ch2en.html', data=data)

@app.route('/en2ch', methods=['GET', 'POST'])
def en2ch():
    loger.info(f'now in english translate to chinese')
    data = {'input': session.get('input', 'hello'), 'output': '你好'}
    if request.method == 'POST':
        session.clear()
        question = request.form.get("inputTxt")
        loger.info(f"get input text {question}")
        translate = translate_en2ch(question)
        data = {'input': question, 'output': translate}
    session['previous_route'] = 'en2ch'
    return render_template('en2ch.html', data=data)


if __name__ == '__main__':
    app.run(debug=False)
